<template>
  <el-dialog v-model="dialogVisible"  width="600px" >
     <Title title="选择分组创建队伍" />
    <div class="dialog-container">
      <el-form :model="form" label-width="auto" ref="formRef" size="large" :rules="rules">
        <el-form-item label="学院" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择学院" @change="onDeptChange" clearable style="width: 100%">
          <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="年级" prop="gradeId">
        <el-select v-model="form.gradeId" placeholder="请选择年级" :disabled="!form.deptId" clearable @change="onGradeChange" style="width: 100%">
          <el-option v-for="item in gradeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="所属分组" prop="groupId">
        <el-select v-model="form.groupId" placeholder="请选择分组" clearable :disabled="!form.deptId" style="width: 100%">
          <el-option v-for="item in groupOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel" :disabled="submitting">取消</el-button>
        <el-button type="primary" @click="confirm" :loading="submitting">进入创建页面</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { listByGrade } from '@/api/group'
import { getGradeTree } from '@/api/grade'
import { ref, getCurrentInstance, computed } from 'vue'
import { useRouter } from 'vue-router'
import Title from '@/components/Title/index.vue'

const router = useRouter()
const groupOptions = ref([])
const { proxy } = getCurrentInstance()

const gradeTree = ref([])
// 学院选项
const deptOptions = computed(() => {
  return gradeTree.value.map((item) => ({
    label: item.deptName,
    value: item.deptId
  }))
})
// 年级选项：根据选中的学院过滤
const gradeOptions = computed(() => {
  if (!form.value.deptId) return []
  const dept = gradeTree.value.find((item) => item.deptId === form.value.deptId)
  return dept ? dept.children.map((grade) => ({ value: grade.gradeId, label: grade.gradeName })) : []
})

const dialogVisible = ref(false)
const formRef = ref(null)
const submitting = ref(false)

const form = ref({
  deptId: '',
  gradeId: '',
  groupId: ''
})

const rules = ref({
  deptId: [{ required: true, message: '请选择学院', trigger: 'change' }],
  gradeId: [{ required: true, message: '请选择年级', trigger: 'change' }],
  groupId: [{ required: true, message: '请选择分组', trigger: 'change' }]
})

const cancel = () => close()

const confirm = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    // 防止重复提交
    if (submitting.value) return
    submitting.value = true

    // 跳转到创建队伍页面，传递 groupId、deptId、gradeId
    router.push({
      path: '/team/create',
      query: {
        groupId: form.value.groupId,
        deptId: form.value.deptId,
        gradeId: form.value.gradeId
      }
    })

    close()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const close = () => {
  dialogVisible.value = false
}

const reset = () => {
  form.value = {
    deptId: '',
    gradeId: '',
    groupId: ''
  }
  groupOptions.value = []
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 加载完整的树形数据
async function loadGradeTree() {
  try {
    const res = await getGradeTree()
    gradeTree.value = res.data || []
  } catch (error) {
    console.error('加载学院年级数据失败:', error)
    gradeTree.value = []
  }
}

// 获取分组列表
async function getGroupList() {
  if (!form.value.deptId) {
    groupOptions.value = []
    return
  }

  try {
    const res = await listByGrade(form.value.gradeId)
    if (res && res.data ) {
      groupOptions.value = res.data.map((item) => ({
        label: item.groupName,
        value: String(item.groupId)
      }))
    } else {
      groupOptions.value = []
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
    proxy.$modal.msgError('获取分组列表失败')
    groupOptions.value = []
  }
}

// 年级改变时的处理
function onGradeChange() {
  form.value.groupId = ''
  groupOptions.value = []
  getGroupList()
}

function onDeptChange() {
  form.value.gradeId = ''
  form.value.groupId = ''
  groupOptions.value = []
}

const openDialog = () => {
  reset()
  dialogVisible.value = true
}

defineExpose({ openDialog })
loadGradeTree()
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
